package com.yazi.mxz.common.entity;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实体属性赋默认值
 * 
 * @author mo_yq5
 * @date 2014-1-10
 */
public class ValueFactory {
	private static Logger log = LoggerFactory.getLogger(ValueFactory.class);

	public static <T> T validate(T obj) {
		Field[] fields = obj.getClass().getDeclaredFields();
		PropertyDescriptor pd = null;
		Method readMethod = null;
		Method writeMethod = null;
		for (Field field : fields) {
			try {
				pd = new PropertyDescriptor(field.getName(),
						field.getDeclaringClass());
				readMethod = pd.getReadMethod();
				writeMethod = pd.getWriteMethod();
				Object value = readMethod.invoke(obj);
				if (null == value && field.getType() != String.class) {
					if (field.getType() == Integer.class) {
						value = new Integer(0);
					} else if (field.getType() == Long.class) {
						value = new Long(0);
					} else if (field.getType() == Float.class) {
						value = new Float(0);
					} else if (field.getType() == Double.class) {
						value = new Double(0);
					} else if (field.getType() == Boolean.class) {
						value = new Boolean(false);
					} else if (field.getType() == Byte.class) {
						value = new Byte((byte) 0);
					} else if (field.getType() == Short.class) {
						value = new Short((short) 0);
					}
					writeMethod.invoke(obj, value);
				}
			} catch (Exception e) {
				log.warn(e.getMessage(), e);
			}
		}

		return obj;
	}

	public static <T> T combine(T from, T to) {
		Field[] fields = from.getClass().getDeclaredFields();
		PropertyDescriptor pd = null;
		Method readMethod = null;
		Method writeMethod = null;
		for (Field field : fields) {
			try {
				pd = new PropertyDescriptor(field.getName(),
						field.getDeclaringClass());
				readMethod = pd.getReadMethod();
				writeMethod = pd.getWriteMethod();
				Object value = readMethod.invoke(from);
				if (null != value ) {
					
					if (value instanceof Set<?> && (((Set<?>) value).isEmpty())) {
						continue;
					}
					
					writeMethod.invoke(to, value);
					
				}
			} catch (Exception e) {
				log.warn(e.getMessage(), e);
			}
		}
		return to;
	}
}
